<template>
  <div class="app-container">
    <div class="tree-box">
      <el-input
        v-model="searchVal"
        class="search-input"
        placeholder="请输入内容"
        prefix-icon="el-icon-search"
        size="small"
        @input="changeSearchVal"
      />
      <el-tree
        :default-expand-all="true"
        :data="treeData"
        :props="{label: 'name'}"
        highlight-current
        @node-click="handleNodeClick"
      />
    </div>
    <div class="table-box">
      <!-- <Tips /> -->
      <tips>
        <template #left>啊就开始了都放假了卡上</template>
        <template #right>
          <el-button type="primary" size="small" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="small" @click="importExcel">excel导入</el-button>
          <el-button size="small" @click="exportExcel">excel导出</el-button>
        </template>
      </tips>
      <!-- 表格 -->
      <!-- <div class="table"> -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="staffPhoto" label="头像" width="100">
          <template slot-scope="scope">
            <img v-if="scope.row.staffPhoto" style="width: 30px" :src="scope.row.staffPhoto" alt />
            <span v-else class="avatar-text">{{ scope.row.username.slice(0, 1) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="100" />
        <el-table-column prop="mobile" hlabel="手机号" width="150" />
        <el-table-column prop="workNumber" label="工号" width="150" />
        <el-table-column
          prop="formOfEmployment"
          :formatter="formateFormOfEmployment"
          label="聘用形式"
          width="100"
        />
        <!-- <el-table-column prop="departmentId" label="部门" width="100" /> -->
        <el-table-column prop="departmentId" :formatter="formateDepartment" label="部门" width="100" />
        <el-table-column prop="timeOfEntry" label="入职时间" width="130" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- <el-button size="mini" type="text" @click="$router.push('/employee/detail?id=7')">查看</el-button> -->
            <el-button
              size="mini"
              type="text"
              @click="$router.push('/employee/detail/'+ scope.row.id)"
            >查看</el-button>
            <el-button size="mini" type="text">角色</el-button>
            <el-button size="mini" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row style="height: 60px" align="middle" type="flex" justify="end">
        <el-pagination
          :current-page.sync="page"
          layout="total,prev, pager, next"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>
    <!-- Excel导入 -->
    <!-- <import-excel ref="import-excel" /> -->
    <!-- <import-excel ref="import-excel" @refresh="getEmployeeList" /> -->
    <import-excel ref="import-excel" @refresh="getLastPage" />
  </div>
  <!-- </div> -->
</template>
<script>
const timerId = null
import Tips from '@/components/Tips/indev.vue'
import { getEmployeeList, getEmployeeExcel, getExportTemplate } from '@/api/employee'
import { getDepartmentList } from '@/api/department'
import { dataToTree2 } from '@/utils/tools'
import { saveAs } from 'file-saver'
import ImportExcel from './components/importExcel.vue'
export default {
  name: 'Employee',
  components: {
    // Employee
    Tips,
    ImportExcel
  },
  data() {
    return {
      timerId: null,
      searchVal: '',
      // 接收原始数据
      department: [],
      tableData: [],
      // 组织数据
      treeData: [],
      props: {
        label: 'name',
        children: 'children'
      },
      // 分页
      page: 1,
      pageSize: 8,
      // 记录员工的总数
      total: 0,
      departmentId: 1
    }
  },
  watch: {
    // 监听用户在搜索框里输入的内容
    searchVal() {
      console.log(2222)
      // this.getEmployeeList()
    }
  },
  created() {
    this.getEmployeeList()
    this.getDepartmentList()
    // this.getEmployeeExcel()
  },
  methods: {
    // 右 头部Excel导入导出
    // 导出
    async exportExcel() {
      const Excel = await getEmployeeExcel()
      // console.log(Excel)
      // eslint-disable-next-line no-undef
      saveAs(Excel, '员工信息.xlsx')
    },
    // 导入
    async importExcel() {
      const res = await getExportTemplate()
      console.log(res)
      this.$refs['import-excel'].open()
    },
    // 右 获取表格数据
    // 将获取到的变量对象用 a 接收渲染页面
    // table
    async getEmployeeList(a) {
      const { data } = await getEmployeeList({
        page: this.page,
        pageSize: this.pagesize,
        // departmentId: a?.departmentId
        // ...a // departmentId: data.id
        // departmentId: this.departmentId
        departmentId: this.departmentId,
        keyword: this.searchVal
      })
      console.log(data)
      this.tableData = data.rows
      this.total = data.total
    },
    // 把聘用形式格式化为文字
    formateFormOfEmployment(row, column, cellValue, index) {
      return cellValue === 1 ? '正式' : '非正式'
    },
    // 当用户改变页码 会执行函数
    handleCurrentChange(val) {
      this.page = val
      console.log(val)
      this.getEmployeeList()
    },
    // 把部门id转换成name
    formateDepartment(row, column, cellValue, index) {
      // 因为有可能渲染表格数据时，getDepartmentList() 还没获取到部门数据
      if (this.department.length === 0) return
      return this.department.find(item => item.id === cellValue).name
    },
    getLastPage() {
      // 方法一： 让total+1再算
      this.page = Math.ceil((this.total + 1) / this.pagesize)

      // 方法二： 向下取整再+1
      // this.page = Math.floor(this.total / this.pagesize) + 1

      this.getEmployeeList()
    },
    // 左侧 搜索框
    // 当用户在搜索框里输入内容后会自动触发
    changeSearchVal() {
      // console.log(111)
      // this.getEmployeeList()
      // 有可能用户当前访问的是后面的页码，但是通过搜索得到的员工数量可能不够，所以每次都得把页码变为1
      // 清除上一个定时器
      clearTimeout(timerId)
      // 再开一个定时器
      // eslint-disable-next-line no-const-assign
      timerId = setTimeout(() => {
        this.page = 1
        this.getEmployeeList()
      }, 3000)
    },
    // 左 获取左侧树状结构
    async getDepartmentList() {
      const { data } = await getDepartmentList()
      // console.log(data)
      // this.data = dataToTree(data)
      // 保存原始一维数组数据
      this.department = data
      // 保存处理后的数据
      this.treeData = dataToTree2(data)
    },
    // 点击左侧节点触发事件
    handleNodeClick(data) {
      // data为点击部门后获取的数据对象
      console.log(data)
      // 获取点击后的数据传送到右侧
      // this.getEmployeeList({
      //   departmentId: data.id
      // })
      // 第一步：先保存departmentId, 当用户点击分页时依然访问的是该部门的员工
      this.departmentId = data.id
      // 第二步：有可能用户当前访问的是后面的页码，但是该部门的员工数量可能不够，所以每次都得把页码变为1
      this.page = 1
      // 第三步：发送请求获取该部门的员工列表
      this.getEmployeeList()
    }
    // 左侧搜索框
  }}
</script>
<style lang="scss" scoped>
.app-container {
  display: flex;
}
.tree-box {
  width: 220px;
  padding: 20px;
  border-right: 2px solid #ccc;
  .search-input {
    margin-bottom: 10px;
  }
}
.table-box {
  flex: 1;
  padding: 10px;
}
// 姓名头像
.avatar-text {
  display: inline-block;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border-radius: 50%;
  background-color: rgb(227, 165, 196);
  color: rgb(3, 98, 165);
}
</style>
